package com.haois.mp.database.module.offaccounts.service;

import com.haois.mp.database.commom.enums.ApiResultEnum;
import com.haois.mp.wechat.common.BusinessRemind;
import com.haois.mp.database.commom.constant.Reply;

import com.haois.mp.database.module.offaccounts.dao.VehicleMapper;
import com.haois.mp.database.module.sdk.api.DriverInfoServer;
import com.haois.mp.database.module.common.daomain.Driver;
import com.haois.mp.database.module.common.daomain.Vehicle;
import com.haois.mp.database.module.wxserver.util.TempMsgUtil;
import com.haois.mp.database.util.jx.DateUtil;
import me.chanjar.weixin.common.exception.WxErrorException;
import com.haois.mp.database.module.common.daomain.Peccancy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * description
 *
 * @author RuiHaoZ on GuangZhou
 * @date 2018/9/2 19:00
 */
@Service
public class VehicleService {

    @Autowired
    private VehicleMapper vehicleMapper;
    @Value("${defined.wxmp.sys-openid}")
    private String sysOpenId;

    public Peccancy getPeccancyById(Integer id) {
        return vehicleMapper.findPeccancyById(id);
    }

    public List<Peccancy> updateAndGetChangeWzInfo(String plate, boolean isDirect) {
        List<Peccancy> newPec = new ArrayList<>();
        Vehicle vehicle = this.findVehicleByPlate(plate);
        if (vehicle != null) {
            vehicle.setWzFen(0);
            vehicle.setWzMoney(0);
            vehicle.setWzSize(0);
            Reply reply = DriverInfoServer.getVehicleInfo(vehicle, isDirect);
            vehicle = (Vehicle) reply.getData();
            if (reply.getCode().equals(ApiResultEnum.API_00.getCode())) {
                Map<String, String> noHandledWz = new HashMap<>();
                List<Peccancy> noHandle = this.findPeccancyBy(null,"0",plate, null,null);
                //所有未处理的违章先设置为已处理
                noHandle.forEach(peccancy -> noHandledWz.put(peccancy.getArchiveno(), "1"));
                List<Peccancy> peccancies = vehicle.getPeccancies();
                Vehicle finalVehicle = vehicle;
                peccancies.forEach(peccancy -> {
                    //所有从数据库中查找到的未处理违章，如果接口有返回处理状态，则替换
                    noHandledWz.put(peccancy.getArchiveno(), peccancy.getHandled());
                    Peccancy p1 = null;
                    if (StringUtils.isNotBlank(peccancy.getArchiveno())) {
                        p1 = vehicleMapper.findPeccancyByArchiveNo(peccancy.getArchiveno());
                    }
                    if (StringUtils.isBlank(peccancy.getArchiveno()) || p1 == null) {
                        p1 = vehicleMapper.findPeccancyByPlateAndDate(peccancy.getVehiclePlate(), peccancy.getDate());
                    }
                    //新发生的的违章记录
                    if (p1 == null) {
                        peccancy.setThisState(1);
                        peccancy.setCreateTime(DateUtil.getYMdHm());
                        newPec.add(peccancy);
                        vehicleMapper.insertPeccancy(peccancy);
                    }
                });
                noHandledWz.forEach((k, v) -> {
                    Peccancy peccancy = vehicleMapper.findPeccancyByArchiveNo(k);
                    if (peccancy == null) {
                        return;
                    }
                    if (v.equals("1")) {
                        peccancy.setThisState(2);
                        peccancy.setHandled("1");
                        peccancy.setUpdateTime(DateUtil.getYMdHm());
                        newPec.add(peccancy);
                        vehicleMapper.updatePeccancy(peccancy);
                    } else {
                        finalVehicle.addWzSize();
                        finalVehicle.addWzMoney(peccancy.getMoney());
                        finalVehicle.addWzFen(peccancy.getFen());
                    }
                });
                this.updateVehicleWzInfo(finalVehicle);
            } else {
                try {
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append("车牌号码：").append(vehicle.getPlate()).append("\n");
                    stringBuffer.append("原因：").append(reply.getMsg()).append("\n");

                    BusinessRemind.remindByWx(new String[]{"车辆违章查询出错", "", stringBuffer.toString()},
                            sysOpenId, TempMsgUtil.title_Sys,
                            TempMsgUtil.temp_Sys, TempMsgUtil.temp_Sys_Color);
                } catch (WxErrorException e) {
                    e.printStackTrace();
                }
            }
        }
        return newPec;
    }

    public List<Driver> findDriver(String memberNum) {
        if (StringUtils.isBlank(memberNum)) {
            return vehicleMapper.findDriver();
        } else {
            return vehicleMapper.findDriverByMem(memberNum);
        }
    }

    public List<Vehicle> findVehicle(String memberNum) {
        if (StringUtils.isBlank(memberNum)) {
            return vehicleMapper.findVehicle();
        } else {
            return vehicleMapper.findVehicleByMem(memberNum);
        }
    }

    public Vehicle findVehicleByPlate(String plate) {
        return vehicleMapper.findVehicleByPlate(plate);
    }

    public List<String> findVehicleMem(int vehId) {
        return vehicleMapper.findMemByVehicle(vehId);
    }

    public List<String> findDriverMem(int dirId) {
        return vehicleMapper.findMemByDriver(dirId);
    }

    public List<Peccancy> findPeccancyBy(String memberNum, String handle, String plate, String beginTime, String endTime) {
        return vehicleMapper.findPeccancyBy(memberNum, handle, plate, beginTime, endTime);
    }

    public void updateDriverScore(int did, int score, String code) {
        Driver driver = new Driver();
        driver.setId(did);
        driver.setScore(score);
        driver.setCode(code);
        driver.setWzUpdateTime(DateUtil.getYMdHm());
        vehicleMapper.updateDriverWzInfo(driver);
    }

    public void updateVehicleWzInfo(Vehicle vehicle) {
        vehicle.setWzUpdateTime(DateUtil.getYMdHms());
        vehicleMapper.updateVehicleWzUpDateTime(vehicle);
    }

    public void updateVehicleInspectTime(Vehicle vehicle, Date nearTime) {
        if (!vehicle.getInspectTime().equals(DateUtil.getYMd(nearTime))) {
            vehicle.setUpdateTime(DateUtil.getYMdHm());
            vehicleMapper.updateVehicleInspectTime(vehicle);
        }
    }

    public Reply insertVehicle(Vehicle vehicle, String memberNum) {
        if (!isRegisterTime(vehicle.getRegister())) {
            return new Reply(ApiResultEnum.API_10.getCode(), "注册时间格式错误");
        }
        Vehicle v1 = vehicleMapper.getVehicleOr(vehicle);
        if (v1 != null) {
            if (!v1.getPlate().equals(vehicle.getPlate())
                    || !v1.getEngineNo().equals(vehicle.getEngineNo())
                    || !v1.getVin().equals(vehicle.getVin())
                    || !v1.getType().equals(vehicle.getType())) {
                return new Reply(ApiResultEnum.API_10.getCode(), "该行驶证已存在，但内容不匹配<br>请仔细核对");
            } else {
                v1.setEmail(vehicle.getEmail());
                v1.setMobile(vehicle.getMobile());
                v1.setOwner(vehicle.getOwner());
                v1.setDossier(vehicle.getDossier());
                v1.setRegister(vehicle.getRegister());
                this.updateVehicle(v1);
                if (isExistVehicleMem(v1.getId(), memberNum)) {
                    this.insertVehicleMem(v1.getId(), memberNum, 0);
                }
                return new Reply(ApiResultEnum.API_00.getCode(), "更新成功", v1);
            }
        } else {
            Reply reply = DriverInfoServer.getVehicleInfo(vehicle, false);
            Vehicle v = (Vehicle) reply.getData();
            if (reply.getCode().equals(ApiResultEnum.API_00.getCode())) {
                vehicle.setCode(v.getCode());
                vehicle.setWzUpdateTime(DateUtil.getYMdHm());
                vehicleMapper.insertVehicle(vehicle);
                this.insertVehicleMem(vehicle.getId(), memberNum, 1);
                return new Reply(ApiResultEnum.API_00.getCode(), "新增成功", v1);
            } else {
                return new Reply(ApiResultEnum.API_00.getCode(), v.getCode());
            }
        }
    }

    public Reply insertDriver(Driver driver, String memberNum) {
        if (!isRegisterTime(driver.getRegister())) {
            return new Reply(ApiResultEnum.API_10.getCode(), "注册时间格式错误");
        }
        Driver d1 = vehicleMapper.getDriverOr(driver);
        if (d1 != null) {
            if (!d1.getLicenseNo().equals(driver.getLicenseNo())
                    || !d1.getDossier().equals(driver.getDossier())) {
                return new Reply(ApiResultEnum.API_10.getCode(), "该驾驶证已存在，但内容不匹配<br>请仔细核对");
            } else {
                d1.setEmail(driver.getEmail());
                d1.setMobile(driver.getMobile());
                d1.setRegister(driver.getRegister());
                d1.setClassModel(driver.getClassModel());
                d1.setName(driver.getName());
                this.updateDriver(d1);
                if (!isExistVehicleMem(d1.getId(), memberNum)) {
                    this.insertDriverMem(d1.getId(), memberNum, 0);
                }
                return new Reply(ApiResultEnum.API_00.getCode(), "更新成功", d1);
            }
        } else {
            Reply reply = DriverInfoServer.getDriverInfo(driver);
            Driver d = (Driver) reply.getData();
            if (reply.getCode().equals(ApiResultEnum.API_00.getCode())) {
                driver.setCreateTime(DateUtil.getYMdHm());
                driver.setCode(d.getCode());
                driver.setScore(d.getScore());
                driver.setWzUpdateTime(DateUtil.getYMdHm());
                vehicleMapper.insertDriver(driver);
                vehicleMapper.insertDriverMem(driver.getId(), memberNum, 1);
                return new Reply(ApiResultEnum.API_00.getCode(), "新增成功", d1);
            } else {
                return new Reply(ApiResultEnum.API_10.getCode(), d.getCode());
            }
        }
    }

    public void insertVehicleMem(int vehicleId, String memberNum, Integer self) {
        vehicleMapper.insertVehicleMem(vehicleId, memberNum, self);
    }

    public void insertDriverMem(int driverId, String memberNum, Integer self) {
        vehicleMapper.insertDriverMem(driverId, memberNum, self);
    }

    public Driver getDriver(Driver driver) {
        return vehicleMapper.getDriver(driver);
    }

    public Vehicle getVehicle(Vehicle vehicle) {
        return vehicleMapper.getVehicle(vehicle);
    }

    public void updateVehicle(Vehicle vehicle) {
        vehicle.setUpdateTime(DateUtil.getYMdHm());
        vehicleMapper.updateVehicle(vehicle);
    }

    public void updateDriver(Driver driver) {
        driver.setUpdateTime(DateUtil.getYMdHm());
        vehicleMapper.updateDriver(driver);
    }

    public boolean isRegisterTime(String register) {
        Date date = DateUtil.stringToDate(register, DateUtil.yMd);
        return date != null;
    }

    public boolean isExistVehicleMem(int vehicleId, String memberNum) {
        Integer c = vehicleMapper.countVehicleMem(vehicleId, memberNum);
        if (c == null || c > 0) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isExistDriverMem(int driverId, String memberNum) {
        Integer c = vehicleMapper.countDriverMem(driverId, memberNum);
        if (c == null || c > 0) {
            return true;
        } else {
            return false;
        }
    }
}
